package cn.jietuo.juc.c_012_varhandle;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/11
 * @description:
 */
public class T01_HelloVarHandle {

    int x = 8;

   private static VarHandle varHandle;

   static{
       try {
           // 固定写法
           varHandle = MethodHandles.lookup().findVarHandle(T01_HelloVarHandle.class,"x",int.class);
       } catch (NoSuchFieldException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       }
   }

    public static void main(String[] args) {
       T01_HelloVarHandle t = new T01_HelloVarHandle();

        System.out.println(varHandle.get(t));
        varHandle.set(t,9);
        System.out.println(t.x);

        varHandle.compareAndSet(t,9,11);
        System.out.println(t.x);

        varHandle.getAndAdd(t,10);
        System.out.println(t.x);
    }

}
